package com.kczd.adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.kczd.client.R;
import com.kczd.entity.Location;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.SlideView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PrivateListingAdapter extends BaseAdapter implements
		SlideView.OnSlideListener {
	private static final String TAG = "SlideAdapter";
	String url = Common.net_addr +"itf/tx_delete_order.php";
	private String okey="";

	private Context mContext;
	private LayoutInflater mInflater;

	private List<Location> mMessageItems = new ArrayList<Location>();
	private SlideView mLastSlideViewWithStatusOn;

	public PrivateListingAdapter(Context context) {
		mContext = context;
		mInflater = LayoutInflater.from(mContext);
	}

	public void setmMessageItems(List<Location> mMessageItems) {
		this.mMessageItems = mMessageItems;
	}

	@Override
	public int getCount() {
		if (mMessageItems == null) {
			mMessageItems = new ArrayList<Location>();
		}
		return mMessageItems.size();
	}

	@Override
	public Object getItem(int position) {
		return mMessageItems.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		SlideView slideView = (SlideView) convertView;
		if (slideView == null) {
			View itemView = mInflater.inflate(R.layout.list_item_order_item,
					null);
			slideView = new SlideView(mContext);
			slideView.setContentView(itemView);

			holder = new ViewHolder(slideView);
			slideView.setOnSlideListener(this);
			slideView.setTag(holder);
		} else {
			holder = (ViewHolder) slideView.getTag();
		}
		Location item = mMessageItems.get(position);
		item.slideView = slideView;
		item.slideView.shrink();

		Location location=(Location) getItem(position);
		okey=location.getOkey();
		holder.typeIV.setImageResource(location.getType());
		holder.datetimeTV.setText(location.getDatetime());
		holder.originTV.setText(location.getOrigin());
		holder.terminalTV.setText(location.getTerminal());
		holder.deleteHolder.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mMessageItems.remove(position);
				new Thread(new Runnable() {
					@Override
					public void run() {
                      deleteHandler();
					}
				}).start();
				notifyDataSetChanged();
			}
		});

		return slideView;
	}

	Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Bundle data = msg.getData();
			String val = data.getString("ret_json");
			val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
			JSONObject jsonResult;
			try {
				jsonResult = new JSONObject(val);
				// UI界面的更新等相关操作
				if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
					String ukey=jsonResult.getString("ukey");
				}else{
					Log.e(TAG,"删除失败");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	/**
	 * 删除订单
	 */
	public void deleteHandler(){
		OkHttpClient okHttpClient = new OkHttpClient();
		RequestBody requestBody=new FormBody.Builder()
				.add("ukey", Common.user.getUkey())
				.add("okey",okey)
				.add("utype",Common.utype)
				.build();
		Request request=new Request.Builder()
				.url(url)
				.post(requestBody)
				.build();
		try {
			Response response=okHttpClient.newCall(request).execute();
			String strResult=response.body().string();
			if(response.code() == 200) {
				Message msg = new Message();
				Bundle data = new Bundle();
				data.putString("ret_json", strResult);
				msg.setData(data);
				handle.sendMessage(msg);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static class ViewHolder {
		ImageView typeIV;
		TextView  datetimeTV;
		TextView  originTV;
		TextView  terminalTV;
		ViewGroup deleteHolder;

		ViewHolder(View view) {
			typeIV=(ImageView) view.findViewById(R.id.iv_type);
			datetimeTV=(TextView) view.findViewById(R.id.tv_date);
		    originTV=(TextView) view.findViewById(R.id.tv_origin);
			terminalTV=(TextView) view.findViewById(R.id.tv_terminal);
			deleteHolder = (ViewGroup) view.findViewById(R.id.holder);
		}
	}

	@Override
	public void onSlide(View view, int status) {
		if (mLastSlideViewWithStatusOn != null
				&& mLastSlideViewWithStatusOn != view) {
			mLastSlideViewWithStatusOn.shrink();
		}

		if (status == SLIDE_STATUS_ON) {
			mLastSlideViewWithStatusOn = (SlideView) view;
		}
	}
}
